//
// Created by Administrator on 2020/7/11.
//T6章:数组、指针与字符串(2)
//动态内存分配
//2:申请和释放动态数组（一）


//eg:动态创建对象数组(一维数组)
/*
#include <iostream>
using namespace std;
class Point
{
public:
    Point():x(0),y(0)
    {
        cout<<"Default Constructor called."<<endl;
    }
    Point(int x,int y):x(x),y(y){cout<<"Constructor called."<<endl;}
    ~Point(){cout<<"Destructor called."<<endl;}
    int getX()const{return x;}
    int getY()const{return y;}
    void move(int newX,int newY)
    {
        x=newX;
        y=newY;
    }
private:
    int x,y;
};
int main()
{
    Point *ptr=new Point[2];//创建对象数组
    ptr[0].move(5,10);//通过指针访问数组元素的成员
    ptr[1].move(15,20);//通过指针访问数据元素的成员
    cout<<"Deleting..."<<endl;
    delete[] ptr;//删除整个对象数组
    return 0;
}
*/


//eg:动态创建对象数组(三维数组)
/*
#include <iostream>
using namespace std;
int main()
{
    int (*cp)[9][8]=new int[7][9][8];
    for(int i=0;i<7;i++)
        for(int j=0;j<9;j++)
            for(int k=0;k<8;k++)
                *(*(*(cp+i)+j)+k)=(i*100+j*10+k);
    for(int i=0;i<7;i++) {
        for (int j = 0; j < 9; j++) {
            for (int k = 0; k < 8; k++)
                cout << cp[i][j][k] << " ";
            cout<<endl;
        }
        cout<<endl;
    }
    delete[] cp;
    return 0;
}
*/



//3:申请和释放动态数组（二）
//将动态数组封装成类
//eg:动态数组类
#include <iostream>
#include <cassert>
using  namespace std;
class Point
{
public:
    Point():x(0),y(0)
    {
        cout<<"Default Constructor called."<<endl;
    }
    Point(int x,int y):x(x),y(y){cout<<"Constructor called."<<endl;}
    ~Point(){cout<<"Destructor called."<<endl;}
    int getX()const{return x;}
    int getY()const{return y;}
    void move(int newX,int newY)
    {
        x=newX;
        y=newY;
    }
private:
    int x,y;
};

class ArrayOfPoints//动态数组类
{
public:
    ArrayOfPoints(int size):size(size)
    {
        points=new Point[size];
    }
    ~ArrayOfPoints() {
        cout << "Deleting..." << endl;
        delete[] points;
    }
    Point& element(int index) {
        assert(index >= 0 && index < size);
        return points[index];
    }
private:
    Point *points;//调用动态数组首地址
    int size;//数组大小
};
int main()
{
    int count;
    cout<<"Please enter the count of point:";
    cin>>count;
    ArrayOfPoints points(count);
    points.element(0).move(5,0);
    points.element(1).move(15,20);
    return 0;
}



